import React, { Component } from 'react';
import { Upload, Modal,message } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import {IMAGE_URL,BASE_URL} from '../../config/index';
import { reqDeletePicture } from '../../api'

function getBase64(file) {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => resolve(reader.result);
        reader.onerror = error => reject(error);
    });
}

class PicturesWall extends Component {
    state = {
        previewVisible: false,//是否展示预览弹窗
        previewImage: '',//需要预览的图片的URL地址或base64编码
        previewTitle: '',//预览图片标题
        fileList: [],
    };
    // 把fileList中的图片名字保存到一个新的数组里
    getImgArr = () => {
        let result = [];
        this.state.fileList.forEach((item) => {
            result.push(item.name)
        });
        return result;
    }
    // set
    setFileList =(imgArr)=>{
        let fileList = [];
        imgArr.forEach((item,index)=>{
            fileList.push( {uid:index,name:item,url:`${IMAGE_URL}${item}`})
        })
        this.setState({fileList})
    }
    // 关闭预览窗
    handleCancel = () => this.setState({ previewVisible: false });
    // 展示预览窗
    handlePreview = async file => {
        if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj);
        }

        this.setState({
        previewImage: file.url || file.preview,
        previewVisible: true,
        previewTitle: file.name || file.url.substring(file.url.lastIndexOf('/') + 1),
        });
    };
    // 当图片状态发生改变的回调
    handleChange = async ({ file,fileList }) =>{
        // 图片上传成功
        console.log(file);
        if(file.status === 'done'){
            fileList[fileList.length-1].url = file.response.url
            fileList[fileList.length-1].name = file.response.url
        }
        // 图片删除时
        if(file.status === 'remove'){
           let result = await reqDeletePicture(file.name)
           const { status,msg } = result;
           if(status === 0 ) message.success('删除图片成功！',1)
           else message.success(msg,1)
        }
        this.setState({ fileList });
    }

    render() {
        const { previewVisible, previewImage, fileList, previewTitle } = this.state;
        const uploadButton = (
        <div>
            <PlusOutlined />
            <div style={{ marginTop: 8 }}>点击上传图片</div>
        </div>
        );
        return (
        <div>
            <Upload
            action={`${BASE_URL}/api/training/upload`} //接受图片服务器的地址
            method="post"
            name="image"
            listType="picture-card"   //照片墙的展示样式
            fileList={fileList}   //图片列表，一个数组里包含的多个图片 对象
            onPreview={this.handlePreview}
            onChange={this.handleChange}  //图片状态改变的回调（图片上传、图片被删除、图片成功上传）
            >
            {fileList.length >= 1 ? null : uploadButton}  
            </Upload>
            <Modal
            visible={previewVisible}
            title={previewTitle}
            footer={null}
            onCancel={this.handleCancel}
            >
            <img alt="example" style={{ width: '100%' }} src={previewImage} />
            </Modal>
        </div>
        );
    }
    }

    export default PicturesWall;